package com.closer.service.biz.ai.core.builder;


import cn.hutool.core.util.RuntimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class VueProjectBuilder {

    public void buildProjectAsync(String projectPath){
        //在单独的线程中执行构建，避免阻塞主流程
        Thread.ofVirtual().name("vue-builder-"+System.currentTimeMillis()).start(()->{
           try{
               buildProject(projectPath);
           } catch (Exception e){
               log.error("异步构建Vue项目时发生异常：{}",e.getMessage(),e);
           }
        });
    }


    /**
     * 执行命令
     * @param workingDir 工作目录
     * @param command 命令字符串
     * @param timeoutSeconds 超时时间（秒）
     * @return 是否执行成功
     */
    private boolean executeCommand(File workingDir, String command, int timeoutSeconds){
        try{
            log.info("在目录{}中执行命令：{}",workingDir.getAbsolutePath(),command);
            var process = RuntimeUtil.exec(
                    null,
                    workingDir,
                    command.split("\\s+") //命令分割为数组
            );
            var finished = process.waitFor(timeoutSeconds, TimeUnit.SECONDS);
            if(!finished){
             log.error("命令执行超时({}秒)，强制终止进程",timeoutSeconds);
             process.destroyForcibly();
             return false;
            }
            var exitCode = process.exitValue();
            if(exitCode == 0){
                log.info("命令执行成功:{}",command);
                return true;
            }else {
                log.error("命令执行失败:{},错误码是：{}，错误信息是：{}",command,exitCode,RuntimeUtil.getErrorResult(process));
                return false;
            }
        }catch (Exception e){
            log.error("执行命令失败：{}时发生异常，错误信息：{}",command,e.getMessage());
            return false;
        }
    }

    /**
     * 执行npm install 命令
     */
    private boolean executeNpmInstall(File projectDir){
        log.info("执行npm install ...");
        var command = String.format("%s install",buildCommand("npm"));
        return executeCommand(projectDir,command,300); //五分钟超时
    }

    /**
     * 执行npm run build 命令
     */
    private boolean executeNpmBuild(File projectDir){
        log.info("执行npm run build ...");
        var command = String.format("%s run build",buildCommand("npm"));
        return executeCommand(projectDir,command,300);
    }

    /**
     * 判断当前操作系统是否是Windows
     */
    private boolean isWindows(){
        return System.getProperty("os.name").toLowerCase().contains("windows");
    }

    private String buildCommand(String baseCommand){
        if (isWindows()){
            return baseCommand+ ".cmd";
        }
        return baseCommand;
    }


    public boolean buildProject(String projectPath){
        var projectDir = new File(projectPath);
        if(!projectDir.exists() || !projectDir.isDirectory()){
            log.error("项目目录不存在：{}",projectPath);
            return false;
        }
        // 检查package.json
        var packageJson = new File(projectDir,"package.json");
        if(!packageJson.exists()){
            log.error("项目目录下不存在package.json文件：{}",projectPath);
            return false;
        }
        log.info("开始构建Vue 项目：{}",projectPath);
        //执行 npm install
        if(!executeNpmInstall(projectDir)){
            log.error("npm install 执行失败");
            return false;
        }
        //执行 npm run build
        if(!executeNpmBuild(projectDir)){
            log.error("npm run build 执行失败");
            return false;
        }
        var distDir = new File(projectDir,"dist");
        if(!distDir.exists()){
            log.error("构建完成但dist目录未生成：{}",distDir.getAbsolutePath());
            return false;
        }
        log.info("Vue项目构建成功，dist目录：{}",distDir.getAbsolutePath());
        return true;
    }
}
